package com.acmedcare.framework.exchange.center.executer.job;

import com.acmedcare.framework.exchange.center.entity.bean.Task;
import com.acmedcare.framework.exchange.center.executer.TaskRunnerManager;
import com.acmedcare.framework.exchange.center.core.storage.TaskRunner;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

@SuppressWarnings("unused")
@Slf4j
public class HealthCheckJob implements Job {

  /**
   * 防止程序被强制关闭，导致程序上运行的任务，没有及时解除注册，固设定补偿机制，定期重置运行标志位置
   */
  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    TaskRunnerManager manager = new TaskRunnerManager();
    List<TaskRunner> runners = manager.getRunning();
    if (runners == null || runners.isEmpty()) {

      return;
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MINUTE, -20);
    Date dueTime = calendar.getTime();
    for (TaskRunner runner : runners) {

      //检查是否存在超过5分钟还没有处理完成的僵尸任务，如果存在，则将僵尸任务直接重新回归标志位。
      if (runner.getUpdateTime().before(dueTime)) {

        Task task = new Task();
        task.setTaskId(runner.getTaskId());
        manager.unRegister(task);
        log.info("僵尸任务：" + runner.getName() + ",完成清理!");
      }
    }
  }
}